import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class ClientGui extends JFrame {

	private JPanel contentPane;
	private JTextField textField;
	private JButton btnSend;
	private static JTextPane textPane;
	private static Socket s;
	private static DataInputStream sockIn;
	private static DataOutputStream sockOut;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ClientGui frame = new ClientGui();
					frame.setVisible(true);
					Connector("localhost", 4592);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 * 
	 * @throws IOException
	 */
	public ClientGui() throws IOException {

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 589, 325);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);

		textField = new JTextField();
		textField.setColumns(10);

		textPane = new JTextPane();
		textPane.setEditable(false);

		btnSend = new JButton("Send");
		btnSend.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (!textField.getText().equals("")) {
					// Writer(textField.getText());
					try {
						sockOut.writeUTF(textField.getText().toString());
						sockOut.flush();
					} catch (IOException | NullPointerException e1) {
						Writer("Something gone bad. Try again late");
					}
					textField.setText("");
				}
			}
		});
      getRootPane().setDefaultButton(btnSend);
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane
				.setHorizontalGroup(gl_contentPane
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								Alignment.TRAILING,
								gl_contentPane
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												gl_contentPane
														.createParallelGroup(
																Alignment.TRAILING)
														.addComponent(
																textPane,
																Alignment.LEADING,
																GroupLayout.DEFAULT_SIZE,
																543,
																Short.MAX_VALUE)
														.addGroup(
																gl_contentPane
																		.createSequentialGroup()
																		.addComponent(
																				textField)
																		.addGap(18)
																		.addComponent(
																				btnSend)))
										.addContainerGap()));
		gl_contentPane
				.setVerticalGroup(gl_contentPane
						.createParallelGroup(Alignment.TRAILING)
						.addGroup(
								gl_contentPane
										.createSequentialGroup()
										.addContainerGap()
										.addComponent(textPane,
												GroupLayout.PREFERRED_SIZE,
												210, GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												ComponentPlacement.RELATED, 27,
												Short.MAX_VALUE)
										.addGroup(
												gl_contentPane
														.createParallelGroup(
																Alignment.BASELINE)
														.addComponent(
																textField,
																GroupLayout.PREFERRED_SIZE,
																29,
																GroupLayout.PREFERRED_SIZE)
														.addComponent(btnSend))));
		contentPane.setLayout(gl_contentPane);
	}

	private static void Connector(String host, int port) {
		boolean connect = true;
		try {
			s = new Socket(host, port);
		} catch (IOException e) {
			Writer("I can't connect. Is server run?");
			connect = false;
		}
		if (connect)
			try {
				sockOut = new DataOutputStream(s.getOutputStream());
				sockIn = new DataInputStream(s.getInputStream());
				new Thread(new ServerReader()).start();
			} catch (IOException e) {
				Writer("Something goes wrong");
			}
	}

	public static void Writer(String line) {
		if (!textPane.getText().equals("")) {
			StringBuilder newText = new StringBuilder();
			newText.append(textPane.getText() + "\n" + line);
			textPane.setText(newText.toString());
		} else
			textPane.setText(line);
	}

	public synchronized static void close() {
		if (!s.isClosed())
			try {
				s.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}

	private static class ServerReader implements Runnable {

		@Override
		public void run() {
			while (true) {
				String line = null;
				try {
					line = sockIn.readUTF();
				} catch (IOException e) {
					if ("Socket closed".equals(e.getMessage())) {
						System.out.println(e.getMessage());
						close();
						break;
					}
				}
				if (line.equals("Server: You was disconected.")) {
					Writer("Server has close connection. Please restart the app.");
					close();
					break;
				} else {
					Writer(line);
				}
			}

		}

	}

}
